package Leetcode;

import java.util.Stack;

/**
 * 给定整数数组 nums 和整数 k，请返回数组中第 k 个最大的元素。
 * 输入: [3,2,1,5,6,4] 和 k = 2
 * 输出: 5
 */
public class 力扣215_数组中的第K个最大元素 {
    public static void main(String[] args) {
        int[] nums = new int[]{3, 2, 1, 5, 6, 4};
        System.out.println(findKthLargest(nums, 2));
    }

    /**
     * 使用栈保存元素
     */
    public static int findKthLargest(int[] nums, int k) {
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < nums.length; i++) {
            if (stack.isEmpty()) {
                stack.push(nums[i]);
            } else {
                Stack<Integer> tempStack = new Stack<>();
                while (!stack.isEmpty()) {
                    Integer peek = stack.peek();
                    if (peek < nums[i]) {
                        tempStack.push(stack.pop());
                    } else {
                        break;
                    }
                }
                tempStack.push(nums[i]);
                while (stack.size() < k && !tempStack.isEmpty()) {
                    stack.push(tempStack.pop());
                }
            }
        }
        return stack.get(k - 1);
    }

    /**
     * 使用快排
     */
    public static int findKthLargest1(int[] nums, int k) {
        if (nums.length < k) {
            return -1;
        }
        力扣912_快排.quickSortDesc(nums);
        return nums[k - 1];
    }


}
